﻿using System.Collections.Generic;
using UnityEngine;

namespace winS.Unity
{
    /// <summary>
    /// 表示函数句柄所有者
    /// </summary>
    public class HandleOwner : MonoBehaviour
    {
        private bool destroying;

        private List<Handle> handleList;

        public void AddHandle(Handle handle)
        {
            if (handleList.Contains(handle)) return;
            handleList.Add(handle);
            handle.onFinished += () =>
            {
                if (destroying) return;
                handleList.Remove(handle);
            };
        }

        private void Awake()
        {
            handleList = new List<Handle>();
        }
        private void OnDestroy()
        {
            destroying = true;
            if (handleList == null) return;//防止编辑器下编译后脚本报空
            foreach (var handle in handleList) handle.Stop();
        }
    }
}